package com.yilemall.product.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.yilemall.common.exception.RRException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.yilemall.product.entity.CategoryEntity;
import com.yilemall.product.service.CategoryService;
import com.yilemall.common.utils.PageUtils;
import com.yilemall.common.utils.R;



/**
 * 商品分类管理
 *
 * @author wangxiaoqi
 * @email wxq_strive@163.com
 * @date 2020-10-09 15:16:45
 */
@Api(value = "商城接口",tags = "商城:商品管理")
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询商品分类列表
     */
    @ApiOperation(value = "查询商品分类列表")
    @GetMapping("/list/tree")
    public R list(){
        List<CategoryEntity> categoryEntityList = categoryService.listWistTree();

        return R.ok().put("data", categoryEntityList);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId){
		CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("data", category);
    }

    /**
     * 修改商品分类
     */
    @ApiOperation(value = "修改商品分类")
    @PostMapping("/update")
    public R update(@Validated @RequestBody CategoryEntity category){
		categoryService.updateDetail(category);

        return R.ok();
    }

    /**
     * 批量修改商品分类(拖拽的时候使用)
     */
    @ApiOperation(value = "批量修改商品分类")
    @PostMapping("/update/sort")
    public R updateSort( @RequestBody CategoryEntity[] category){
        categoryService.updateBatchById(Arrays.asList(category));

        return R.ok();
    }

    /**
     * 保存商品分类
     */
    @ApiOperation(value = "保存商品分类")
    @PostMapping("/save")
    public R save(@Validated @RequestBody CategoryEntity category){
        boolean checkResult = categoryService.checkCategory(category.getParentCid());

        if(!checkResult) throw new RRException("分类最多能添加2级");

        categoryService.saveOrUpdate(category);

        return R.ok();
    }

    /**
     * 删除未被引用的菜单
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
		//categoryService.removeByIds(Arrays.asList(catIds));
        //检查当前删除菜单，是否被别的地方引用
        categoryService.removeMenuByIds(Arrays.asList(catIds));
        return R.ok();
    }

}
